package org.lex.ftp.queue;

import java.io.File;
import javax.swing.ActionMap;

import org.lex.ftp.FTP;
import org.lex.ftp.util.Actions;
import org.lex.net.ftp.FTPFile;
import org.lex.net.ftp.IFTPFile;


public class QueueUtils {
	public static void setTransferring(FTP app, boolean transfer) {
		ActionMap am = app.getActionMap();
		am.get(Actions.ABORT).setEnabled(transfer);
		am.get(Actions.TRANSFER).setEnabled(!transfer);
	}

	/***************************************************************************
	 * Methods to add download tasks to queue
	 **************************************************************************/
	public static void downloadSelected(FTP app) {
		IFTPFile[] files = app.getFTPExplorer().getFileExplorer().getSelectedFiles();
		app.getQueue().addLast(createDownloadTasks(app, files));
	}

	public static void downloadCurrentCatalog(FTP app) {
		IFTPFile[] files = app.getFTPExplorer().getFileExplorer().getAllFiles();
		app.getQueue().addFirst(createDownloadTasks(app, files));
	}

	public static DownloadTask[] createDownloadTasks(FTP app, IFTPFile[] files) {
		DownloadTask[] tasks = new DownloadTask[files.length];
		for (int i = 0; i < tasks.length; i++)
			tasks[i] = createDownloadTask(app, files[i]);
		return tasks;
	}

	public static DownloadTask createDownloadTask(FTP app, IFTPFile file) {
		String ftpPath = app.getFTPExplorer().getFTPModel().getCatalog();
		File dir = app.getFileExplorer().getDirectory();
		File localFile = new File(dir, file.getName());
		return new DownloadTask(app, ftpPath, file, localFile);
	}

	/***************************************************************************
	 * Methods to add upload tasks to queue
	 **************************************************************************/
	public static void uploadSelected(FTP app) {
		File[] files = app.getFileExplorer().getFileExplorer().getSelectedFiles();
		app.getQueue().addLast(createUploadTask(app, files));
	}

	public static void uploadCurrentDirectory(FTP app) {

	}

	public static UploadTask[] createUploadTask(FTP app, File[] files) {
		UploadTask[] tasks = new UploadTask[files.length];
		for (int i = 0; i < tasks.length; i++)
			tasks[i] = createUploadTask(app, files[i]);
		return tasks;
	}

	public static UploadTask createUploadTask(FTP app, File file) {
		String ftpPath = app.getFTPExplorer().getFTPModel().getCatalog();
		IFTPFile ftpFile = FTPFile.newFile(ftpPath, file.getName(), file.isDirectory());
		return new UploadTask(app, ftpPath, ftpFile, file);
	}

	private QueueUtils() {
	}
}
